package io.github.talelin.latticy.common.interceptor;

import io.github.talelin.autoconfigure.interfaces.LoggerResolver;
import io.github.talelin.core.annotation.Logger;
import io.github.talelin.core.annotation.PermissionMeta;
import io.github.talelin.core.util.BeanUtil;
import io.github.talelin.latticy.common.LocalUser;
import io.github.talelin.latticy.common.handler.MyInvocationHandler;
import io.github.talelin.latticy.common.util.CharUtil;
import io.github.talelin.latticy.common.util.HttpHelper;
import io.github.talelin.latticy.common.util.SpringContextUtils;
import io.github.talelin.latticy.conf.MyBaseMapper;
import io.github.talelin.latticy.model.UserDO;
import io.github.talelin.latticy.service.LogService;
import io.github.talelin.latticy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author pedro@TaleLin
 * @author Juzi@TaleLin
 * @author colorful@TaleLin
 */
@Slf4j
@Component
public class LoggerImpl implements LoggerResolver {

    private static ArrayList<String> wmsPath = new ArrayList<String>(Arrays.asList("/toWritePath"));

    @Autowired
    private LogService logService;

//    @Autowired
//    private OpenFeignService openFeignService;

    @Autowired
    private UserService userService;

    /**
     * 日志格式匹配正则
     */
    private static final Pattern LOG_PATTERN = Pattern.compile("(?<=\\{)[^}]*(?=})");

    @Override
    public void handle(PermissionMeta meta, Logger logger, HttpServletRequest request, HttpServletResponse response) {
        String template = logger.template();
        UserDO user = LocalUser.getLocalUser();
        template = this.parseTemplate(template, user, request, response);
        String permission = "";
        if (meta != null) {
            permission = !StringUtils.hasLength(meta.value()) ? meta.value() : meta.value();
        }
        Integer userId = user.getId();
        String username = user.getUsername();
        String method = request.getMethod();
        String path = request.getServletPath();
        Integer status = response.getStatus();
        logService.createLog(template, permission, userId, username, method, path, status);
    }

    private String parseTemplate(String template, UserDO user, HttpServletRequest request, HttpServletResponse response) {
        // 调用 get 方法
        Matcher m = LOG_PATTERN.matcher(template);
        while (m.find()) {
            String group = m.group();
            String property = this.extractProperty(group, user, request, response);
            template = template.replace("{" + group + "}", property);
        }
        return template;
    }

    private String extractProperty(String item, UserDO user, HttpServletRequest request, HttpServletResponse response) {
        int i = item.lastIndexOf('.');
        String obj = item.substring(0, i);
        String prop = item.substring(i + 1);
        switch (obj) {
            case "user":
                if (user == null) {
                    return "";
                }
                return BeanUtil.getValueByPropName(user, prop);
            case "request":
                return methodRoute(request, prop);
            case "response":
                return BeanUtil.getValueByPropName(response, prop);
            default:
                return "";
        }
    }

    private String methodRoute(HttpServletRequest request, String prop) {
        String method = request.getMethod().toLowerCase();
        switch (method) {
            case "put":
//                return putMethodAnalysis(request, prop);
            case "delete":
                return deleteMethodAnalysis(request, prop);
            case "post":
                return HttpHelper.getBodyParamByProp(request, prop);
            default:
                return "";
        }
    }

//    private String putMethodAnalysis(HttpServletRequest request, String prop) {
//        String pathVariableValue = HttpHelper.getPathVariableParamByProp(request, prop);
//        if (!prop.equals("id")) {
//            return pathVariableValue;
//        }
//        /**
//         * 返回调用servlet的部分url
//         */
//        String servletPath = request.getServletPath();
//        String subPath = CharUtil.subPathOver3(servletPath, "/");
//        UserDO userDO;
//        if (wmsPath.contains(subPath)) {
////            userDO = openFeignService.getOmsUserAfterLogById(Integer.parseInt(pathVariableValue));
//            userDO=new UserDO();
//        } else {
//            userDO = userService.getById(Integer.parseInt(pathVariableValue));
//        }
//        return Optional.ofNullable(userDO.getUsername()).orElse("");
//    }

    private String deleteMethodAnalysis(HttpServletRequest request, String prop) {
        String pathVariableValue = HttpHelper.getPathVariableParamByProp(request, "id");
        /**
         * if 行为日志：记录当前服务删除操作的时候，需要携带xxxMapper,并用-标识
         * else  行为日志:  记录RPC生产者，被调用方日志的时候无需携带-
         * 跨服务调用行为日志只能记录用户信息
         */
        if (prop.contains("-")) {
            int i = prop.lastIndexOf('-');
            String objMapper = prop.substring(0, i);
            String key = prop.substring(i + 1);
            Object proxyMapper = SpringContextUtils.getBean(objMapper);
            MyInvocationHandler proxy = new MyInvocationHandler(proxyMapper);
            MyBaseMapper instance = (MyBaseMapper) proxy.Instance();
            Object obj = instance.selectLogicById(Integer.parseInt(pathVariableValue));
            if (obj != null) {
                return CharUtil.getKey(obj.toString(), key);
            }
        }else {
            /**
             * 返回调用servlet的部分url
             */
            String servletPath = request.getServletPath();
            String subPath = CharUtil.subPathOver3(servletPath, "/");
            UserDO userDO;
            if (wmsPath.contains(subPath)) {
//                userDO = openFeignService.getOmsUserAfterLogById(Integer.parseInt(pathVariableValue));
                userDO=new UserDO();
            } else {
                userDO = userService.getById(Integer.parseInt(pathVariableValue));
            }
            return Optional.ofNullable(userDO.getUsername()).orElse("");
        }
        return pathVariableValue;
    }
}
